package com.atguigu.lease.common.converter;

import com.atguigu.lease.model.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

/**
 * @author hzq
 * @version 1.0
 * @description:
 * @date 2024/8/12 16:34
 */
//todo:配置转换器工厂
@Component
public class StringToBaseEnumConverter implements ConverterFactory<String, BaseEnum> {
    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        return new Converter<String, T>() {
            @Override
            public T convert(String source) {
               //获取枚举实例
                T[] enumConstants = targetType.getEnumConstants();
                //遍历
                for (T enumConstant : enumConstants) {
                    //判断
                    if (enumConstant.getCode().equals(Integer.parseInt(source))) {
                        return enumConstant;
                    }
                }
                return null;
            }
        };
    }
}
